package com.avic.modules.storage;


import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

/**
 * 服务器本地对象存储服务
 */
public class LocalServerStorage {

    private String storagePath; // 存储路径
    private String address; // 文件地址
    private Path rootLocation;

    public String getStoragePath() {
        return storagePath;
    }

    public void setStoragePath(String storagePath) {
        this.storagePath = storagePath;
        this.rootLocation = Paths.get(storagePath);
        try {
            Files.createDirectories(rootLocation);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public void store(InputStream inputStream, String keyName) {
        try {
            Files.copy(inputStream, rootLocation.resolve(keyName), StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            throw new RuntimeException("Failed to store file " + keyName, e);
        }
    }


    public Path load(String filename) {
        return rootLocation.resolve(filename);
    }

    public void delete(String filename) {
        Path file = load(filename);
        try {
            Files.delete(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String generateUrl(String keyName) {
        String url = address + keyName;
        return url;
    }

    public static void main(String[] args) throws IOException {
        // resource
        File testFile = new File("localstorage/files/test.txt");
        System.out.println(testFile.getAbsolutePath());

        LocalServerStorage localServerStorage = new LocalServerStorage();
        localServerStorage.setStoragePath("localstorage/files");
        localServerStorage.setAddress("localstorage/files/");
        System.out.println(localServerStorage.generateUrl("test.txt"));
    }
}